import { Button, Form, Input, Table, Space, Flex, Tag, Layout, theme, Tree } from 'antd'
import { useEffect, useState, useCallback } from 'react'
import { findAllCategory } from '@/api/category'
import { findAllArticle, deleteArticle } from '@/api/article'
import ArticleEditor from './articleEditor'
import useConfirmModal from '@/hooks/useConfirmModal'
import FormButton from '@/components/formButton'
import ContentWrapper from '@/components/ContentWrapper'
import { useRef } from 'react'

const { Sider, Content } = Layout

const ArticleList = () => {
  const [treeData, setTreeData] = useState([])
  const [dataSource, setDataSource] = useState([])
  const [articleModalVisible, setArticleModalVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState('')
  const [articleId, setArticleId] = useState('')
  const {
    token: { colorBgContainer }
  } = theme.useToken()
  const confirmModal = useConfirmModal()
  const childRef = useRef(null)

  const handleOpenModal = (title, article_id) => {
    setModalTitle(title)
    setArticleId(article_id)
    setArticleModalVisible(true)
  }

  const getCategoryList = useCallback(async () => {
    const { data } = await findAllCategory({ type: 'tree' })
    setTreeData(data)
  }, [])

  const getArticleList = useCallback(async () => {
    const { data } = await findAllArticle()
    setDataSource(data)
  }, [])

  const handleDeleteArticle = (id) => {
    confirmModal(async () => {
      await deleteArticle({ id })
      getArticleList()
    })
  }

  useEffect(() => {
    getCategoryList()
    getArticleList()
  }, [getCategoryList, getArticleList])

  const columns = [
    {
      title: '序号',
      dataIndex: 'category_id',
      width: 50,
      align: 'center',
      render: (text, record, index) => {
        return index + 1
      }
    },
    {
      title: '文章分类',
      dataIndex: 'category_id',
      align: 'center'
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      align: 'center'
    },
    {
      title: '文章内容',
      dataIndex: 'content',
      align: 'center'
    },
    {
      title: '文章状态',
      dataIndex: 'status',
      align: 'center',
      render: (text) => {
        const isActive = text === 1
        return <Tag color={isActive ? 'success' : 'error'}>{isActive ? '已发布' : '草稿'}</Tag>
      }
    },
    {
      title: '创建人',
      dataIndex: 'created_by',
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      align: 'center'
    },
    {
      title: '最后更新人',
      dataIndex: 'updated_by',
      align: 'center'
    },
    {
      title: '最后更新时间',
      dataIndex: 'updated_at',
      align: 'center'
    },
    {
      title: '排序',
      dataIndex: 'sort_order',
      align: 'center'
    },
    {
      title: '操作',
      fixed: 'right',
      width: 240,
      align: 'center',
      render: (text, record) => {
        const { article_id } = record
        return <Flex gap="small" justify="center">
          <Button color="blue" variant='filled' size="small" onClick={() => handleOpenModal('编辑文章', article_id)}>编辑</Button>
          <Button color="red" variant='filled' size="small" onClick={() => handleDeleteArticle(article_id)}>删除</Button>
          <Button color="green" variant='filled' size="small" onClick={() => handleOpenModal('文章详情', article_id)}>详情</Button>
          <Button color="orange" variant='filled' size="small" onClick={() => handleOpenModal('文章详情', article_id)}>发布</Button>
        </Flex>
      }
    }
  ]

  const onFinish = (values) => {
    console.log('Success:', values)
  }

  const onOk = async () => {
    await childRef.current.confirm()
    getArticleList()
    setArticleModalVisible(false)
  }

  const exportData = () => {
    console.log('导出')
  }

  const importData = () => {
    console.log('导入')
  }

  const downloadData = () => {
    console.log('下载')
  }

  return <Layout>
    <Sider className="layout-sider-tree">
      <Tree
        fieldNames={{
          title: 'name',
          key: 'category_id',
          children: 'children'
        }}
        treeData={treeData}
      />
    </Sider>

    <div className="line"></div>

    <Content
      style={{
        margin: '0',
        padding: 24,
        minHeight: 280,
        background: colorBgContainer
      }}
    >
      <Space direction="vertical" size="middle">
        <Form layout="inline" onFinish={onFinish}>
          <Form.Item
            label="文章名称"
            name="name"
          >
            <Input placeholder="文章名称" />
          </Form.Item>

          <Form.Item>
            <FormButton
              search={getArticleList}
              add={() => handleOpenModal('新增文章')}
              export={exportData}
              import={importData}
              download={downloadData}
            />
          </Form.Item>
        </Form>

        <Table
          bordered
          columns={columns}
          dataSource={dataSource}
          rowKey="article_id"
          size="small"
          scroll={{ x: 'max-content' }}
        />
      </Space>

      {
        articleModalVisible &&
        <ContentWrapper
          title={modalTitle}
          onCancel={() => setArticleModalVisible(false)}
          onOk={onOk}
        >
          <ArticleEditor
            ref={childRef}
            isDetail={Boolean(modalTitle.includes('详情'))}
            article_id={articleId}
            treeData={treeData}
          />
        </ContentWrapper>
      }
    </Content>
  </Layout>
}

export default ArticleList